<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="最近项目中,需要做一个基于UDP的请求响应这样的应答模型. HTTP本身就是支持请求-响应模型的,但是TCP和UDP不是. 经过一番思考和讨论,提出了2个解决方案，这个地方做一个记录.我相信我这个方案应该不是最好的，都有各自的缺陷。如果你有更好的解决方案，还请不吝赐教。  基于JUC的Lock和Condition 基于Future的get   为山九仞，功亏一篑！">
<meta name="keywords" content="请求响应">
<meta property="og:type" content="article">
<meta property="og:title" content="基于TCP&#x2F;UDP的请求响应模型设计">
<meta property="og:url" content="http://yoursite.com/2018/07/12/udp-req-res/index.html">
<meta property="og:site_name" content="ThinkMore">
<meta property="og:description" content="最近项目中,需要做一个基于UDP的请求响应这样的应答模型. HTTP本身就是支持请求-响应模型的,但是TCP和UDP不是. 经过一番思考和讨论,提出了2个解决方案，这个地方做一个记录.我相信我这个方案应该不是最好的，都有各自的缺陷。如果你有更好的解决方案，还请不吝赐教。  基于JUC的Lock和Condition 基于Future的get   为山九仞，功亏一篑！">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/%E5%9F%BA%E4%BA%8E%E7%BD%91%E7%BB%9C%E7%9A%84%E8%AF%B7%E6%B1%82%E5%92%8C%E5%93%8D%E5%BA%94.png">
<meta property="og:updated_time" content="2018-07-30T08:01:18.641Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于TCP&#x2F;UDP的请求响应模型设计">
<meta name="twitter:description" content="最近项目中,需要做一个基于UDP的请求响应这样的应答模型. HTTP本身就是支持请求-响应模型的,但是TCP和UDP不是. 经过一番思考和讨论,提出了2个解决方案，这个地方做一个记录.我相信我这个方案应该不是最好的，都有各自的缺陷。如果你有更好的解决方案，还请不吝赐教。  基于JUC的Lock和Condition 基于Future的get   为山九仞，功亏一篑！">
<meta name="twitter:image" content="http://p5h71khzd.bkt.clouddn.com/%E5%9F%BA%E4%BA%8E%E7%BD%91%E7%BB%9C%E7%9A%84%E8%AF%B7%E6%B1%82%E5%92%8C%E5%93%8D%E5%BA%94.png">






  <link rel="canonical" href="http://yoursite.com/2018/07/12/udp-req-res/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>基于TCP/UDP的请求响应模型设计 | ThinkMore</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?13172698bcdb7ab00b7d3ec112aae9c1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ThinkMore</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">驽马十驾,功在不舍！</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/07/12/udp-req-res/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="文敦复">
      <meta itemprop="description" content="思考的懒惰是真的懒惰！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ThinkMore">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">基于TCP/UDP的请求响应模型设计
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2018-07-12 17:39:30" itemprop="dateCreated datePublished" datetime="2018-07-12T17:39:30+08:00">2018-07-12</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2018-07-30 16:01:18" itemprop="dateModified" datetime="2018-07-30T16:01:18+08:00">2018-07-30</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/解决方案/" itemprop="url" rel="index"><span itemprop="name">解决方案</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>最近项目中,需要做一个基于<code>UDP</code>的<code>请求响应</code>这样的应答模型.</p>
<p><code>HTTP</code>本身就是支持<code>请求-响应模型</code>的,但是TCP和UDP不是.</p>
<p>经过一番思考和讨论,提出了2个解决方案，这个地方做一个记录.我相信我这个方案应该不是最好的，都有各自的缺陷。如果你有更好的解决方案，还请不吝赐教。</p>
<ul>
<li>基于<code>JUC</code>的<code>Lock</code>和<code>Condition</code></li>
<li>基于<code>Future</code>的<code>get</code></li>
</ul>
<blockquote>
<p>为山九仞，功亏一篑！</p>
</blockquote>
<a id="more"></a>
<h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><p>该项目是基于<code>Netty</code>的,以下会有<code>Netty</code>的几个知识点:</p>
<ol>
<li><code>SimpleChannelInboundHandler.channelRead0()</code>该方法会在<code>Netty</code>接收到消息的时候被触发，希望从这个地方获取到消息ID，并唤醒阻塞的程序。</li>
<li><code>channel.writeAndFlush(object)</code>该方法是将消息通过<code>channel</code>发给出去。</li>
<li>项目启动类，请注意其中的<code>AgentContext</code>，用来保存<code>channel</code>方便随时发送信息出去。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">EventLoopGroup group = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">Bootstrap bootstrap = <span class="keyword">new</span> Bootstrap();</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	Channel channel = bootstrap.group(group).channel(NioSocketChannel.class)</span><br><span class="line">	                    .option(ChannelOption.TCP_NODELAY, <span class="keyword">true</span>)</span><br><span class="line">	                    .handler(<span class="keyword">new</span> AgentChannelInitializer(<span class="keyword">new</span> TcpReceivedHandler()))</span><br><span class="line">	                    .connect(innerIp, innerPort)</span><br><span class="line">	                    .sync().channel();</span><br><span class="line">	<span class="comment">//将channel保存,用于后续的消息发送</span></span><br><span class="line">	AgentContext.setChannel(channel);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>发送的对象和接收的对象一致,以下为大概的模型<code>CmdBo</code></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CmdBo</span></span>&#123;</span><br><span class="line">    <span class="comment">//唯一主键,建议通过uuid生成</span></span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="comment">//请求体</span></span><br><span class="line">    <span class="keyword">private</span> String request;</span><br><span class="line">    <span class="comment">//响应内容</span></span><br><span class="line">    <span class="keyword">private</span> String response;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="方法一：通过lock和condition"><a href="#方法一：通过lock和condition" class="headerlink" title="方法一：通过lock和condition"></a>方法一：通过lock和condition</h1><p>方案一上下文有2个关联，用于存储关联信息：</p>
<ul>
<li>一个是<code>id</code>同<code>控制量</code>的关联<code>ControlContext</code></li>
<li>另外一个是<code>id</code>同<code>结果</code>的关联:<code>ResultContext</code></li>
</ul>
<p>其大体流程为：</p>
<ol>
<li>发送消息时候，生成一个唯一的id.</li>
<li>发送后阻塞，并将id同控制变量进行关联到<code>ControlContext</code>中</li>
<li>接收消息时候，有2个操作：一个是解析出消息中的id，并将id同结果绑定。二是获取id对应的控制变量，将阻塞放开，后续从结果<code>ResultMap</code>中获取。</li>
</ol>
<p>整体流程图如下所示:</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/%E5%9F%BA%E4%BA%8E%E7%BD%91%E7%BB%9C%E7%9A%84%E8%AF%B7%E6%B1%82%E5%92%8C%E5%93%8D%E5%BA%94.png" alt="基于网络的请求和响应图"></p>
<p><code>Sendor</code>的部分的代码如下所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> CmdBo <span class="title">send</span><span class="params">(CmdBo cmdbo)</span> </span>&#123;</span><br><span class="line">	Lock lock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line">	Condition condition = lock.newCondition();</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		String id = cmdBo.getId();</span><br><span class="line">		ControlContext.put(id, lock, condition);</span><br><span class="line">		lock.lock();</span><br><span class="line">		Channel channel = XXContenxt.CHANNEL;</span><br><span class="line">		channel.writeAndFlush(xxx);</span><br><span class="line">		<span class="comment">//阻塞 </span></span><br><span class="line">		condition.await();</span><br><span class="line">		<span class="comment">// 被唤醒后，从结果上下文中根据id获取结果内容</span></span><br><span class="line">		CmdBo result = ResultContext.getResult(id);</span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>receive</code>部分的代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">channelRead0</span><span class="params">(ChannelHandlerContext ctx, DatagramPacket packet)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	String body = packet.content().toString(CharsetUtil.UTF_8);</span><br><span class="line">	CmdBo bo = JSONUtil.toBean(body, CmdBo.class);</span><br><span class="line">	String id = bo.getId();</span><br><span class="line">    <span class="comment">//将结果放在ResultContext的上下文对象中</span></span><br><span class="line">	ResultContext.put(id, messageBo);</span><br><span class="line">    <span class="comment">//通过id获取控制对象</span></span><br><span class="line">	Tuple2&lt;Lock, Condition&gt; tuple2 = ControlContext.get(id);</span><br><span class="line">	Lock lock = tuple2.first;</span><br><span class="line">	Condition condition = tuple2.second;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		lock.lock();</span><br><span class="line">        <span class="comment">//唤醒sendor阻塞的现成</span></span><br><span class="line">		condition.signal();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">		lock.unlock();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Sendor sendor=<span class="keyword">new</span> Sendor();</span><br><span class="line">CmdBo result=sendor.send(xxx); <span class="comment">//此处会一直阻塞到有结果返回。</span></span><br></pre></td></tr></table></figure>
<p>上述使用到了：<code>Lock</code>和<code>Condition</code>2个知识点，不懂的可以自行百度，这里不展开讲。</p>
<p>上述使用还存在细节问题：</p>
<ol>
<li>上下文的Map，使用完了需要清理。</li>
<li>超时问题，当前处理方式，会导致线程一直被阻塞住。</li>
</ol>
<h1 id="方法二：Future-CountdownLatch"><a href="#方法二：Future-CountdownLatch" class="headerlink" title="方法二：Future+CountdownLatch"></a>方法二：Future+CountdownLatch</h1><p>第二种方案比第一种方案好点，利用了<code>Future</code>,其思路同第一个大致相似，不过通过<code>CountDownlatch</code>来控制阻塞。</p>
<p>首先构建<code>SyncFuture</code>对象,核心代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncFuture</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Future</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 因为请求和响应是一一对应的，因此初始化CountDownLatch值为1。</span></span><br><span class="line">    <span class="keyword">private</span> CountDownLatch latch = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 需要响应线程设置的响应结果</span></span><br><span class="line">    <span class="keyword">private</span> T response;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 获取响应结果，直到有结果才返回。</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        latch.await();</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.response;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取响应结果，直到有结果或者超过指定时间就返回。</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">(<span class="keyword">long</span> timeout, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (latch.await(timeout, unit)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.response;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 用于设置响应结果，并且做countDown操作，通知请求线程</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setResponse</span><span class="params">(T response)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.response = response;</span><br><span class="line">        latch.countDown();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Sendor</code>部分代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> SyncFuture&lt;MessageBo&gt; <span class="title">send</span><span class="params">(MessageBo message)</span> </span>&#123;</span><br><span class="line">	Channel channel = XXContenxt.CHANNEL;</span><br><span class="line">	<span class="comment">//创建future对象并保存</span></span><br><span class="line">	SyncFuture&lt;MessageBo&gt; future = <span class="keyword">new</span> SyncFuture&lt;&gt;();</span><br><span class="line">    <span class="comment">//id同future映射保存到上下文中</span></span><br><span class="line">	FutureContext.addFuture(message.getId(), future);</span><br><span class="line">	<span class="comment">//发送</span></span><br><span class="line">	channel.writeAndFlush(xxx);</span><br><span class="line">	<span class="keyword">return</span> future;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Receiver</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">channelRead0</span><span class="params">(ChannelHandlerContext ctx, DatagramPacket packet)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	String body = packet.content().toString(CharsetUtil.UTF_8);</span><br><span class="line">	<span class="comment">//System.out.println("客户端收到消息:" + body);</span></span><br><span class="line">	CmdBo bo = JSONUtil.toBean(body, CmdBo.class);</span><br><span class="line">	String id = bo.getId();</span><br><span class="line">    <span class="comment">//获取future</span></span><br><span class="line">	SyncFuture future = FutureContext.getFuture(id);</span><br><span class="line">    <span class="comment">//填充future</span></span><br><span class="line">	future.setResponse(messageBo);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用方式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Sendor sendor=<span class="keyword">new</span> Sendor();</span><br><span class="line">SyncFuture&lt;MessageBo&gt; future = sendor.send(mock);</span><br><span class="line">future.get();<span class="comment">//该方法会一直阻塞</span></span><br><span class="line">future.get(<span class="number">4</span>,TimeUnit.Seconds);<span class="comment">//阻塞一定的时间，推荐使用。</span></span><br></pre></td></tr></table></figure>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>上述2种方式大同小异，都是在发送后阻塞，然后从获取的结果内容中进行线程唤醒。</p>
<p>个人感觉应该不属于最好的解决方案，如果你有更好的解决方案，请提出来，大家一起学习。</p>
<blockquote>
<p>您有任何建议和意见，请Email联系: <a href="mailto:hicode_club@163.com" target="_blank" rel="noopener">hicode_club@163.com</a></p>
<p>转载请保留出处 <a href="http://www.hicode.club" target="_blank" rel="noopener">HiCode 俱乐部</a>：<a href="http://www.hicode.club" target="_blank" rel="noopener">http://www.hicode.club</a></p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/10/ffbfwjg-thoughts-1/" rel="next" title="读书笔记-分布式服务-1">
                <i class="fa fa-chevron-left"></i> 读书笔记-分布式服务-1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/07/15/pure-feign-hello-world/" rel="prev" title="使用原生的Feign进行HTTP调用">
                使用原生的Feign进行HTTP调用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">文敦复</p>
              <p class="site-description motion-element" itemprop="description">思考的懒惰是真的懒惰！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">categories</span>
                  
                </div>
              

              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#方法一：通过lock和condition"><span class="nav-number">2.</span> <span class="nav-text">方法一：通过lock和condition</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#方法二：Future-CountdownLatch"><span class="nav-number">3.</span> <span class="nav-text">方法二：Future+CountdownLatch</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文敦复</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Muse</a> v6.4.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
